<?php
/**
 * User: ppjun378
 * Data: 20190102
 * Time: 15:00
 */
namespace App\Service;

use App\Model\Pictures;
use App\Model\PicturesCategorys;
use \Exception;

class PicturesService
{
    /**
     * 获取图片数据
     * @parama $request
     * @return mixed
     * @author ppjun378 <ppjun378@foxmail.com>
     */
    public static function dataList($request, $pic_type = 1)
    {
        $token = $request->input('token', '');
        $login_type_id = $request->input('login_type_id', 1);
        if (empty($token)) {
            $list['code'] = 1;
            $list['msg'] = 'error:用户token不能为空！';
            return $list;
        }
        // 查询微信用户ID
        $wxuser_id = WxusersService::getWxuserId($token);

        if (empty($wxuser_id)) {
            $list['code'] = 1;
            $list['msg'] = 'error:请填写正确的token！';
            return $list;
        }

        $resume_id = $request->input('resume_id', '');

        $fields = [
            'pictures_categorys.id as pictures_categorys_id', // 图片类型编号
            'resume_id', //简历表编号
            'img_url', // 图片地址
            'img_type', // 图片类型
            'img_alt', // 图片描述
            'name as picture_category_name', //图片名称
        ];
        $data = PicturesCategorys::select($fields)
            ->leftJoin('pictures', function ($join) use ($resume_id) {
                $join->on('pictures.img_type', '=', 'pictures_categorys.id')
                    ->where('resume_id', $resume_id);
            })

            ->where('pic_type', $pic_type)
            ->orderBy('pictures_categorys.id', 'asc')
            ->get();

        $list['code'] = 0;
        $list['msg'] = '查询成功';
        $list['count'] = count($data);
        $data = empty($data) ? array() : $data->toArray();

        if (!empty($data)) {
            foreach ($data as $key => $val) {
                $pictures_categorys_id = $val['pictures_categorys_id'];
                if ($pictures_categorys_id == 1) {
                    unset($val['pictures_categorys_id']);
                    $list['data']['profile_picture'] = $val;
                } elseif ($pictures_categorys_id == 4) {
                    unset($val['pictures_categorys_id']);
                    $list['data']['resume_attachment'] = $val;
                } else {
                    unset($val['pictures_categorys_id']);
                    $list['data']['full_length_photograph'][] = $val;
                }
            }
        } else {
            $list['data']['profile_picture'] = [];
            $list['data']['resume_attachment'] = [];
            $list['data']['full_length_photograph'] = [];
        }

        return $list;
    }

    /**
     * 添加/更新
     * @param $request
     * @return mixed
     * @author ppjun378 <ppjun378@foxmail.com>
     */
    public static function store($request, $pic_type = 1)
    {
        $token = $request->input('token', '');
        $login_type_id = $request->input('login_type_id', 1);
        if (empty($token)) {
            $list['code'] = 1;
            $list['msg'] = 'error:用户token不能为空！';
            return $list;
        }
        // 查询微信用户ID
        $wxuser_id = WxusersService::getWxuserId($token);

        if (empty($wxuser_id)) {
            $list['code'] = 1;
            $list['msg'] = 'error:请填写正确的token！';
            return $list;
        }

        $data = $request->all();
        $resume_id = $request->input('resume_id', '');
        $img_type = $request->input('img_type', '');
        $img_alt = $request->input('img_alt', '');
        $map = [];
        $fields = [
            'resume_id', // 简历编号
            'img_url', // 图片地址
            'img_type', // 图片类型
            'img_alt', // 图片描
        ];
        // print_r($fields);

        foreach ($data as $k => $v) {
            if ($v === null) {$v = '';}
            if (in_array($k, $fields) && !empty($v)) {
                $map[$k] = $v;
            }
        }
        // print_r($map);

        $img_info = self::upload_image($request, $pic_type);

        if (empty($img_info['status'])) {

            $list['code'] = 1;
            $list['msg'] = $img_info['message'];
            return $list;

        }

        $map['img_url'] = $img_info['img_url'];

        switch ($img_type) {
            case 1:
                $map['img_alt'] = empty($img_alt) ? '证件照' : $img_alt;
                break;
            case 2:
                $map['img_alt'] = empty($img_alt) ? '全身照1' : $img_alt;
                break;
            case 3:
                $map['img_alt'] = empty($img_alt) ? '全身照2' : $img_alt;
            case 4:
                $map['img_alt'] = empty($img_alt) ? '证件照' : $img_alt;
                break;
        }

        $data_exist = Pictures::where(['resume_id' => $resume_id, 'img_type' => $img_type])->first();
        if ($resume_id && $data_exist) {
            $result = Pictures::where(['resume_id' => $resume_id, 'img_type' => $img_type])->update($map);

            $list['code'] = 0;
            $list['msg'] = 'success';
            $list['data'] = array('img_url' => $map['img_url']);

            return $list;
        } else {

            $result = Pictures::create($map);

            $list['code'] = 0;
            $list['msg'] = 'success';
            $list['data'] = array('img_url' => $map['img_url']);
            return $list;
        }
    }

    /**
     * 删除
     * @param $request
     * @return bool\int
     * @author ppjun378 <ppjun378@foxmail.com>
     */
    public static function destory($request)
    {
        $id = $request->input('id', '');
        $res = Pictures::destory($id);
        if ($res > 0) {
            return $res;
        } else {
            return $false;
        }
    }

    /**
     * 恢复删除
     * @param $request
     * @return $mixed
     * @author ppjun378 <ppjun378@foxmail.com>
     */
    public static function restore($request)
    {
        $id = $request->input('id', '');
        $res = Pictures::where('id', $id)->restore();
        return $res;
    }

    /**
     * 上传图片
     *
     */
    public static function upload_image($request, $pic_type = 1)
    {

        try {

            $fileCharater = $request->file('img_url');

            if (empty($fileCharater)) {
                throw new Exception('请选择一个图片');
                exit;
            }

            //检测上传的文件是否合肥，返回为true或false
            if (!$fileCharater->isValid()) {
                throw new Exception('非法文件');
                exit;

            }

            //获取上传文件大小
            $filesize = $fileCharater->getClientSize();
            if ($filesize * 1 / 1024 > 2 * 1024) {
                throw new Exception('图片不能超过2M');
                exit;

            }

            //获取文件的扩展名
            $ext = $fileCharater->getClientOriginalExtension();

            //获取文件的绝对路径
            $path = $fileCharater->getRealPath();

            if ($pic_type == 2) {
                $rule = ['doc', 'docx', 'xls', 'xlsx'];
                if (!in_array($ext, $rule)) {
                    throw new \Exception('附件格式必须为.doc,.docx,.xls,.xlsx');
                }
            } else {
                $rule = ['jpg', 'png', 'gif', 'jpeg'];
                if (!in_array($ext, $rule)) {
                    throw new \Exception('图片格式必须为.jpg,.png,.gif,.jpeg');
                    exit;
                }
            }

            //定义文件名
            $filename = date('Ymdhis') . '.' . $ext;

            $img_url = 'http://trm.inforward.com.cn/storage/' . $filename;

            //存储文件。disk里面的public。总的来说，就是调用disk模块里的public配置
            \Storage::disk('public')->put($filename, file_get_contents($path));

            $data['img_url'] = $img_url;
            $data['status'] = 1;
            $data['message'] = '上传成功';

            return $data;

        } catch (Exception $exception) {
            $msg = $exception->getMessage();
            $dada['status'] = 0;
            $data['message'] = $msg;

        }
        return $data;

    }

}
